package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.storage.TccOnlinePuton;
import com.ys.entity.sys.YsCol;
import com.ys.service.storage.TccOnlinePutonService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.ToolUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 线上质检上架
 */
@Controller
@RequestMapping("/api/inter/tccOnlinePuton")
public class ApiInterTccOnlinePutonController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccOnlinePutonController.class);

    @Autowired
    private CommonApiService<TccOnlinePuton> commonApiService;

    @Autowired
    private TccOnlinePutonService tccOnlinePutonService;

    //菜单id
    private Long menuId = MenuId.TCC_OnlinePuton;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccOnlinePuton:view";
    private final String PERMISSIONS_DOQUALITY = "tccOnlinePuton:doQualityTesting";//质检上架
    //private final String PERMISSIONS_SETCHW = "tccOnlinePuton:setChw";//设置货位
    private final String PERMISSIONS_BACK = "tccOnlinePuton:back";//回退

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccOnlinePuton setSeachSql(TccOnlinePuton cond) throws Exception{
        cond = tccOnlinePutonService.setSeachSqlByCommon(cond);
        //排序
        cond.setOrderby("A.Bid DESC");
        //权限
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccOnlinePuton cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccOnlinePuton cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccOnlinePuton> util = new ExportExcelUtils<>(new TccOnlinePuton());
            String toFilePath = util.exportExcel(listData, listField, "线上质检上架");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 线上质检上架
     */
    @RequiresPermissions(PERMISSIONS_DOQUALITY)
    @RequestMapping("/doQualityTesting")
    @ResponseBody
    public R errorHandle(HttpServletRequest request, String chw, String choooseDatas){
        try {
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            //根据母表id去重
            List<Map<String, Object>> groupsByJSONArray = ToolUtil.groupsByJSONArray(detailJA,e->e.get("id")!=null?e.get("id").toString():"");
            int doCount = 0;
            //String resMsg = "";
            StringBuffer resMsg = new StringBuffer();
            for (int i = 0; i < groupsByJSONArray.size(); i++) {
                Map<String, Object> detailJO = groupsByJSONArray.get(i);
                Map<String, Object> params = new HashMap<>();
                params.put("id",detailJO.get("id"));
                params.put("chw",chw);
                //线上质检上架
                R res = tccOnlinePutonService.doQualityTesting(params);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg.append("单号：")
                            .append(detailJO.get("bid")!=null?detailJO.get("bid"):"")
                            .append("；")
                            .append(res.getMsg())
                            .append("</br>");
                }
            }
            resMsg = new StringBuffer().append("成功质检上架").append(doCount).append("条数据</br>").append(resMsg);
            return R.ok(resMsg.toString());
        } catch (IllegalArgumentException e) {
            logger.error("IllegalArgumentException出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (RuntimeException e) {
            logger.error("RuntimeException出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 组装回退
     */
    @RequiresPermissions(PERMISSIONS_BACK)
    @RequestMapping("/back")
    @ResponseBody
    public R back(HttpServletRequest request, String chw, String choooseDatas){
        try {
            JSONArray detailJA = JSON.parseArray(choooseDatas);
            //根据母表id去重
            List<Map<String, Object>> groupsByJSONArray = ToolUtil.groupsByJSONArray(detailJA,e->e.get("id")!=null?e.get("id").toString():"");
            int doCount = 0;
            //String resMsg = "";
            StringBuffer resMsg = new StringBuffer();
            for (int i = 0; i < groupsByJSONArray.size(); i++) {
                Map<String, Object> detailJO = groupsByJSONArray.get(i);
                //组装回退
                R res = tccOnlinePutonService.back(Long.parseLong(detailJO.get("id").toString()));
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg.append("单号：")
                            .append(detailJO.get("bid")!=null?detailJO.get("bid"):"")
                            .append("；")
                            .append(res.getMsg())
                            .append("</br>");
                }
            }
            resMsg = new StringBuffer().append("成功组装回退").append(doCount).append("条数据</br>").append(resMsg);
            return R.ok(resMsg.toString());
        } catch (IllegalArgumentException e) {
            logger.error("IllegalArgumentException出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (RuntimeException e) {
            logger.error("RuntimeException出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 设置货位
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/setChw")
    @ResponseBody
    public R setChw(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //上架审核
            return tccOnlinePutonService.setChw(params);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




}